<template>
  <div class="article-body-container">
    <article class="article-body">
      <h2>{{ title }}</h2>
      <!-- 显示文章的副标题，如果存在的话 -->
      <!-- <p v-if="subtitle" class="article-subtitle">{{ subtitle }}</p> -->

    </article>
  </div>
  <div v-html="document" class="article-content"></div>
  <div>
    <!-- <q-page padding>
      <div>
        {{ "SQL编码：" + sqlCode }}
      </div>
      <div>
        {{ "标题：" + title }}
      </div>
      <div>
        {{ "文档测试：" + document }}
      </div>

    </q-page> -->
  </div>
</template>
<script setup>
import { useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { useQuasar } from "quasar";
import { computed, onBeforeMount, onMounted, ref } from "vue";
import { exportFile } from "quasar";
import { date } from "quasar";
import { onBeforeRouteUpdate } from "vue-router";
import { FormatDateTime } from "src/utils/date";
import { postAction } from "src/utils/requestAction";
import DcParam from "src/components/DcParam/DcParam.vue";
import * as XLSX from "xlsx";

const $q = useQuasar();
const { t } = useI18n();
const $route = useRoute();
const loading = ref(false);
const loadingParams = ref(false);
const sqlCode = ref($route.meta.sql_code);
const document = ref($route.meta.document);
const title = ref($route.meta.title);
// console.log("测试sql编码");
// console.log($route.meta);
const tableData = ref([]);
const columnsFromSql = ref([]);
const sqlParams = ref([]);
const queryParams = ref([]);
const userParams = ref({});
const pageOptions = ref([10, 20, 35, 50, 100, 0]);
const memo = ref("");
const mktArea = ref("");
const dept = ref("");
const dutyZone = ref("");

/* const queryParamsWithoutInternal = computed(() => {
  return queryParams.value.filter((item) => {
    return item.sqlparam_code !== "internal";
  });
});

const pagination = ref({
  sortBy: "sort",
  descending: false,
  page: 1,
  rowsPerPage: 20,
}); */

// 获取SQL详细信息，主要是其关联的参数和SQL的memo列
//不能注释，关系到左侧的菜单树
const RequestSqlInfo = async () => {
  loading.value = true;
  loadingParams.value = true;
  await postAction("sql/query-sql-by-sql-code", {
    sql_code: sqlCode.value,
  }).then((res) => {
    if (res.code === 1) {
      // console.log("测试sql信息");
      // console.log(res.data.records);
      memo.value = res.data.records.memo;
      sqlParams.value = res.data.records.sqlparam;
      console.log(sqlParams.value);
      queryParams.value = [];
      /*       sqlParams.value.forEach((item) => {
              queryParams.value.push({
                sqlparam_code: item.sqlparam_code,
                value: item.default_value,
                sqlparam_name: item.sqlparam_name,
                sqlparam_type: item.sqlparam_type,
              });
              userParams.value[item.sqlparam_code] = item.default_value;
            }
            ); */
      loadingParams.value = false;
    }
  });
};

// 获取报表的列属性
// const RequestColumnInfo = async () => {
//   loading.value = true;
//   await postAction("sql/query-sql-columns-by-sql-code", {
//     sql_code: sqlCode.value,
//   }).then((res) => {
//     if (res.code === 1) {
//       columnsFromSql.value = res.data.records;
//       // console.log(columnsFromSql.value);
//     }
//   });
// };

// 获取报表的表数据
// const RequestSqlData = async (params) => {
//   loading.value = true;
//   await postAction("sql/query-sql-result-by-sql-code", {
//     sql_code: sqlCode.value,
//     params: params,
//   }).then((res) => {
//     if (res.code === 1) {
//       tableData.value = res.data.records || [];
//       pagination.value.rowsNumber = res.data.total;
//     }
//     loading.value = false;
//   });
// };

// const columns = computed(() => {
//   return columnsFromSql.value.map((item) => {
//     return {
//       name: item.column_name,
//       label: item.column_name,
//       field: item.column_name,
//       sortable: true,
//       align: "center",
//       width: "100px",
//       format: (val, row) => {
//         if (item.data_type === "datetime") {
//           return `${FormatDateTime(val)}`;
//         } else {
//           return `${val}`;
//         }
//       },
//     };
//   });
// });

/* const onRequest = (props) => {
  console.log(props.params);
  RequestSqlData(props.params);
};

const handleSearch = () => {
  console.log(queryParams.value);
  RequestSqlData(queryParams.value);
};
const resetSearch = () => {
  queryParams.value = {};
  RequestSqlData(queryParams.value);
};
 */
/* onMounted(() => {
  RequestSqlInfo().then(() => {
    console.log(queryParams.value);
    RequestColumnInfo().then(() => {
      RequestSqlData(queryParams.value);
    });
  });

}); */

/* const routerUpdateWatch = onBeforeRouteUpdate(async (to, from) => {
  console.log(to.meta.sql_code);
  console.log(from.meta.sql_code);
  if (to.meta.sql_code !== from.meta.sql_code) {
    sqlCode.value = to.meta.sql_code;
    RequestSqlInfo().then(() => {
      RequestColumnInfo().then(() => {
        RequestSqlData(queryParams.value);
      });
    });
  }
}); */

/* const wrapCsvValue = (val, formatFn) => {
  let formatted = formatFn !== void 0 ? formatFn(val) : val;
  formatted =
    formatted === void 0 || formatted === null ? "" : String(formatted);
  formatted = formatted.split('"').join('""');
  return `"${formatted}"`;
}; */

/* const exportXlsx = () => {
  // Create a new Workbook
  const wb = XLSX.utils.book_new();

  // Convert your data to a worksheet
  const wsData = [
    columns.value.map((col) => col.label),
    ...tableData.value.map((row) =>
      columns.value.map((col) =>
        typeof col.field === "function"
          ? col.field(row)
          : row[col.field === void 0 ? col.name : col.field]
      )
    ),
  ];

  const ws = XLSX.utils.aoa_to_sheet(wsData);

  // Define cell format as text for all cells (s: "text")
  ws["!cols"] = [{ s: { numFmt: "s" } }];

  // Add the worksheet to the workbook
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

  // Generate the Excel file as a buffer
  const xlsxfile = XLSX.write(wb, { bookType: "xlsx", type: "buffer" });

  // Export the Excel file
  const status = exportFile(
    $route.meta.sql_code +
    date.formatDate(Date.now(), "YYYY-MM-DD-HH-mm-ss") +
    ".xlsx",
    xlsxfile,
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  );

  if (status !== true) {
    $q.notify({
      message: "浏览器拒绝了文件下载...",
      color: "negative",
      icon: "warning",
    });
  }
}; */

/* const exportCsv = () => {
  // naive encoding to csv format
  const content = [columns.value.map((col) => wrapCsvValue(col.label))]
    .concat(
      tableData.value.map((row) =>
        columns.value
          .map((col) =>
            wrapCsvValue(
              typeof col.field === "function"
                ? col.field(row)
                : row[col.field === void 0 ? col.name : col.field],
              col.format
            )
          )
          .join(",")
      )
    )
    .join("\r\n");
  const status = exportFile(
    $route.meta.sql_code +
    date.formatDate(Date.now(), "YYYY-MM-DD-HH-mm-ss") +
    ".csv",
    content,
    "text/csv"
  );
  if (status !== true) {
    $q.notify({
      message: "浏览器拒绝了文件下载...",
      color: "negative",
      icon: "warning",
    });
  }
}; */
</script>

<script>
import { defineComponent } from "vue";

export default defineComponent({
  name: "queryComp",
});
</script>

<style scoped>
.article-body-container {
  padding: 20px;
  max-width: 800px;
  margin: auto;
}

.article-body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  line-height: 1.6;
  color: #333;
}

.article-body h2 {
  font-size: 40px;
  color: #027be3;
  margin-bottom: 20px;
}

/*.article-body .article-subtitle {
  font-size: 18px;
  color: #666;
  margin-bottom: 15px;
}*/

.article-content {
  white-space: pre-wrap;
  /* 保留空白符 */
  font-size: 18px;
  /* 调整正文字体大小 */
  text-align: left;
  /* 靠左对齐 */
  margin-bottom: 16px;
  padding-left: 25px;
  /* 左边预留空白 */
  padding-right: 25px;
  /* 右边预留空白 */
}

.article-content p,
.article-content ul,
.article-content ol {
  margin-bottom: 16px;
}

.article-content a {
  color: #0645AD;
  text-decoration: none;
}

.article-content a:hover {
  text-decoration: underline;
}
</style>
